﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using Yahoo.Yui.Compressor;
using Yahoo_Compressor.Properties;

namespace Yahoo_Compressor
{
    public partial class MainForm : Form
    {
        public const string StyleSheetExtension = ".css";
        public const string JavaScriptExtension = ".js";


        public MainForm()
        {
            InitializeComponent();
        }

        private bool IsJavascriptFile(string filename)
        {
            return string.Compare(GetExtension(filename), JavaScriptExtension, true) == 0;
        }

        private bool IsStyleSheetFile(string filename)
        {
            return string.Compare(GetExtension(filename), StyleSheetExtension, true) == 0;
        }

        private string GetExtension(string filename)
        {
            var pointIndex = filename.LastIndexOf('.');
            if (pointIndex < 0)
                return string.Empty;
            return filename.Substring(pointIndex);
        }

        private string GetMiniFileName(string filename)
        {
            if (IsJavascriptFile(filename))
            {
                return filename.Replace(GetExtension(filename), Settings.Default.JavaScriptCompactExtension);
            }
            else if (IsStyleSheetFile(filename))
            {
                return filename.Replace(GetExtension(filename), Settings.Default.StyleSheetCompactExtension);
            }
            else
            {
                return string.Empty;
            }
        }

        private string CompressJavascript(string filename)
        {
            Encoding encoding = null;
            switch (Settings.Default.JavaScriptEncoding)
            {
                case "ASCII":
                    encoding = Encoding.ASCII;
                    break;
                case "Unicode":
                    encoding = Encoding.Unicode;
                    break;
                case "UTF32":
                    encoding = Encoding.UTF32;
                    break;
                case "UTF7":
                    encoding = Encoding.UTF7;
                    break;
                case "UTF8":
                    encoding = Encoding.UTF8;
                    break;
                default:
                    encoding = Encoding.Unicode;
                    break;
            }

            return JavaScriptCompressor.Compress(File.ReadAllText(filename), Settings.Default.JavaScriptIsVerboseLogging,
                Settings.Default.JavaScriptIsObfuscateJavascript, Settings.Default.JavaScriptPreserveAllSemicolons,
                Settings.Default.JavaScriptDisableOptimizations, Convert.ToInt32(Settings.Default.JavaScriptLineBreakPosition), encoding,
                System.Threading.Thread.CurrentThread.CurrentCulture, Settings.Default.JavaScriptIsEvalIgnored);
        }

        private string CompressStylesheet(string filename)
        {
            return CssCompressor.Compress(File.ReadAllText(filename),
                Convert.ToInt32(Settings.Default.StyleSheetColumnWidth), Settings.Default.StyleSheetCssCompressionType, Settings.Default.StyleSheetRemoveComments);
        }

        private void fileAreaLabel_DragLeave(object sender, EventArgs e)
        {
        }

        private void fileAreaLabel_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
                e.Effect = DragDropEffects.Copy;
        }

        private void fileAreaLabel_DragDrop(object sender, DragEventArgs e)
        {
            try
            {
                var items = e.Data.GetData(DataFormats.FileDrop) as string[];
                var filenames = new List<String>();
                foreach (var item in items)
                {
                    if (Directory.Exists(item))
                    {
                        filenames.AddRange(Directory.GetFiles(item, "*.*", SearchOption.AllDirectories));
                    }
                    else if (File.Exists(item))
                    {
                        filenames.Add(item);
                    }
                }

                BatchCompress(filenames);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void BatchCompress(IEnumerable<string> filenames)
        {
            foreach (var file in filenames)
            {
                var miniFileName = GetMiniFileName(file);
                if (IsJavascriptFile(file))
                {
                    File.WriteAllText(miniFileName, CompressJavascript(file));
                }
                else if (IsStyleSheetFile(file))
                {
                    File.WriteAllText(miniFileName, CompressStylesheet(file));
                }
            }
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void optionsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (var options = new OptionsForm())
            {
                options.ShowDialog(this);
            }
        }

        private void addFilesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (var browse = new OpenFileDialog())
            {
                browse.Multiselect = true;
                browse.Filter = "All Website Script Files|*.js;*.css|JavaScript Files|*.js|StyleSheet Files|*.css|All Files|*.*";
                if (browse.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    BatchCompress(browse.FileNames);
                    MessageBox.Show(string.Format("Compressing {0} files completed successfully.", browse.FileNames.Length), "Complete",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }

        private void addDirectoryToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (var browse = new FolderBrowserDialog())
            {
                if (browse.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    var files = Directory.GetFiles(browse.SelectedPath, "*.*", SearchOption.AllDirectories);
                    BatchCompress(files);
                    MessageBox.Show(string.Format("Compressing {0} files completed successfully.", files.Length), "Complete",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }
    }
}
